import { APIUserList, apiGetAdminLogin } from "@/api/interface"
import router from "@/router"
import { usePermissionStoreHook } from "@/store/modules/permission"
import cache from "@/utils/cache"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import Speech from "@/utils/speech"
import { defineStore } from "pinia"

// cache 代表浏览器缓存
const permissionStore = usePermissionStoreHook()

export const useUserStore = defineStore("userStore", {
  state: () => ({
    // 用户信息
    user: cache.getUser(),
    // token
    token: getToken(),
    roles: []
  }),

  actions: {
    setUser(val: any) {
      this.user = val
    },
    setToken(val: any) {
      this.token = val
    },
    setRoles(value: any) {
      // level：1 超级管理员 level：2 项目管理员 level：3 项目会员
      const rolesArr = {
        1: ["超级管理员"],
        2: ["项目管理员"],
        3: ["项目会员"]
      } as any
      this.roles = rolesArr[value]
      permissionStore.setRoutes(rolesArr[value])
    },
    // 手机号登录
    async login(loginForm: any) {
      const { mobile_numb, sms, rememberToLogIn } = loginForm
      const { data, code } = await apiGetAdminLogin({ mobile_numb, sms })
      if (code !== 200) return
      // this.setToken(data.token)
      setToken(data.token, rememberToLogIn) //token存cookies
      this.getInfo()
    },

    // 获取用户信息
    async getInfo() {
      const { messages, data } = await APIUserList()
      this.setUser(data)
      console.log(messages, data, "userInfo ")
      cache.setUser(data)
      // this.setRoles(messages.level)
    },

    // 用户退出
    async logout() {
      // 移除 token
      this.setToken(null)
      removeToken()
      // 退出登录时，关闭socket链接
      Speech.instance.close()
      router.push("/login")
    },
    /** 重置 Token */
    async resetToken() {
      removeToken()
      this.setToken(null)
      this.setRoles([])
    }
  }
})
